from web import models
from django.core.exceptions import ValidationError
from utils.bootstrap import BootstrapModelForm,BootstrapForm

class FileModelForm(BootstrapModelForm):
    class Meta:
        model = models.FileRepository
        fields=['name',]

    def __init__(self,request,parent_object,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request = request
        self.parent_object = parent_object

    def clean_name(self):
        name = self.cleaned_data["name"]
        # 判断数据库中 当前目录下是否存在同名目录
        # 先查询当前目录下的文件夹名称
        queryset = models.FileRepository.objects.filter(name=name,file_type=2,project=self.request.tracer.project)
        if self.parent_object:
            # 如果进去了某个目录，这样过滤
            exists = queryset.filter(parent=self.parent_object).exists()
        else:
            exists = queryset.filter(parent__isnull=True).exists()
        if exists:
            raise ValidationError("已存在同名文件夹")
        return name